# -*- coding: utf-8 -*-

# @Project : UI_KDTFrameWork
# @Author  : Mr.Deng
# @Time    : 2021/9/26 20:56

from tools.operateConfig import OperateConfig
from tools.logConfig import Logger
from config.filePathConfig import *

from selenium import webdriver


class Driver:

    def __init__(self):
        self.Log = Logger().origin_logger
        self.cf = OperateConfig()
        self.cf_browser = self.cf.read_config_data(browserConfig)

        # 浏览器名称等待加载时间
        self.defaultName = self.cf_browser.get("browser", "name", fallback="Chrome")
        self.waitTime = self.cf_browser.getint("browser", "wait_time", fallback=10)

        # 浏览器配置
        self.isHeadless = self.cf_browser.getboolean("browser", "headless", fallback=False)
        self.isPwdAlert = self.cf_browser.getboolean("browser", "disable_info", fallback=False)
        self.isAutoAlert = self.cf_browser.getboolean("browser", "automation", fallback=False)

        # 手机模式配置
        self.iPhoneName = self.cf_browser.get("browser", "iphone_name", fallback="iPhone 8")
        self.width = self.cf_browser.getint("browser", "width", fallback=350)
        self.height = self.cf_browser.getint("browser", "height", fallback=700)

        # 获取浏览器驱动路径
        cf_driver = self.cf.read_config_data(driverStartPath)
        self.chromeDriverPath = cf_driver.get("driver_path", "chrome_driver_path", fallback=None)
        self.firefoxDriverPath = cf_driver.get("driver_path", "chrome_driver_path", fallback=None)
        self.ieDriverPath = cf_driver.get("driver_path", "chrome_driver_path", fallback=None)

    def open_browser(self, browserName, isH5="pc"):
        """
        打开浏览器
        :param isH5: 是否打开手机模式
        :param browserName: 浏览器名称
        :return
        """

        if self.chromeDriverPath is None:
            self.Log.warning("浏览器驱动获取异常，正在重新下载匹配当前浏览器版本驱动，请稍后...")
            """ 
            这里调用下载驱动功能
            """

        isH5 = True if isH5 == "h5" else False
        options = self.set_browser(browserName=browserName, isH5=isH5)

        if browserName == "Chrome":
            driverLoadPath = self.chromeDriverPath
        elif browserName == "Firefox":
            driverLoadPath = self.firefoxDriverPath
        elif browserName == "Ie":
            driverLoadPath = self.ieDriverPath
        else:
            driverLoadPath = self.chromeDriverPath

        # 打开浏览器
        try:
            driver = getattr(webdriver, browserName)(executable_path=driverLoadPath, options=options)
        except:
            driver = getattr(webdriver, self.defaultName)(executable_path=self.chromeDriverPath, options=options)
            self.Log.warning(f"浏览器启动名称：{browserName} 不正确，默认启动 Chrome 浏览器...")

        # 设置浏览器H5打开大小
        if isH5:
            driver.set_window_size(self.width, self.height)
        else:
            driver.maximize_window()

        return driver

    def set_browser(self, browserName: str, isH5: bool):
        """
        设置浏览器配置信息
        :param browserName: 浏览器名称
        :param isH5: 默认PC浏览器
        :return:
        eg:
        set_browser(isH5 = "h5") 打开浏览器为手机模式
        """
        # 打开浏览器类型
        if browserName.lower() == "chrome":
            options = webdriver.ChromeOptions()
        elif browserName.lower() == "firefox":
            options = webdriver.FirefoxOptions()
        elif browserName.lower() == "ie":
            options = webdriver.IeOptions()
        else:
            options = webdriver.ChromeOptions()

        # 关闭浏览器无头模式，True为打开
        options.headless = self.isHeadless

        # 其他浏览器配置，关闭账号密码保存弹窗
        usePwdAlert = {
            "credentials_enable_service": self.isPwdAlert,
            "profile.password_manager_enabled": self.isPwdAlert,
        }
        options.add_experimental_option("prefs", usePwdAlert)

        # 打开手机模式
        if isH5:
            mobileEmulation = {"deviceName": self.iPhoneName}
            options.add_experimental_option("mobileEmulation", mobileEmulation)

        # 关闭自动化控制提示
        if not self.isAutoAlert:
            options.add_experimental_option("excludeSwitches", ['enable-automation'])

        # linux运行chrome
        options.add_argument('no-sandbox')

        return options
